package com.easyfun.healthmagicbox.bluetooth;


import java.sql.SQLException;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.easyfun.healthmagicbox.HealthBoxApplication;
import com.easyfun.healthmagicbox.R;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.inputviews.HardwareInputActivity;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.HealthInputTypeEnum;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.util.HealthDateUtil;
import com.iflytek.speech.ErrorCode;
import com.iflytek.speech.ISpeechModule;
import com.iflytek.speech.InitListener;
import com.iflytek.speech.SpeechConstant;
import com.iflytek.speech.SpeechSynthesizer;
import com.iflytek.speech.SynthesizerListener;
import com.j256.ormlite.dao.Dao;

public abstract class BTMessageHandler extends Handler{
	protected String m_personid;
	protected Context mContext;
	private static final String TAG = BTMessageHandler.class.getSimpleName();

	private BluetoothChatService mbluechat;
	// 初始化合成对象

	private SpeechSynthesizer mTts =null;
	private Object mConnectedDeviceName;
	protected static HardwareInputActivity parent;
	/**
	 * 初期化监听。
	 */
	private InitListener mTtsInitListener = new InitListener() {

		@Override
		public void onInit(ISpeechModule arg0, int code) {
			Log.d(TAG, "InitListener init() code = " + code);
			if (code == ErrorCode.SUCCESS) {
				Log.d(TAG, "TTS intialized Successfully!");
			}
		}
	};
	/**
	 * 合成回调监听。
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener.Stub() {
		@Override
		public void onBufferProgress(int progress) throws RemoteException {
			Log.d(TAG, "onBufferProgress :" + progress);
			showTip("onBufferProgress :" + progress);
		}

		@Override
		public void onCompleted(int code) throws RemoteException {
			Log.d(TAG, "onCompleted code =" + code);
			showTip("onCompleted code =" + code);
		}

		@Override
		public void onSpeakBegin() throws RemoteException {
			Log.d(TAG, "onSpeakBegin");
			showTip("onSpeakBegin");
		}

		@Override
		public void onSpeakPaused() throws RemoteException {
			Log.d(TAG, "onSpeakPaused.");
			showTip("onSpeakPaused.");
		}

		@Override
		public void onSpeakProgress(int progress) throws RemoteException {
			Log.d(TAG, "onSpeakProgress :" + progress);
			showTip("onSpeakProgress :" + progress);
		}

		@Override
		public void onSpeakResumed() throws RemoteException {
			Log.d(TAG, "onSpeakResumed.");
			showTip("onSpeakResumed");
		}
	};
	
	public BTMessageHandler(String personID, Context context, HardwareInputActivity _parent)
	{
		m_personid = personID;
		mContext = context;
		parent = _parent;
		mTts = new SpeechSynthesizer(mContext,
					mTtsInitListener);
	}

	/**
	 * _W:75kg_ _H:123mm;L:75mm;B:80_ _G:4.7_
	 * 
	 * @param readMessage
	 */
	protected void sound(HealthInputData hid) {
		

//			mTts.setParameter(SpeechConstant.ENGINE_TYPE, "local");
//			mTts.setParameter(SpeechSynthesizer.VOICE_NAME, "xiaoyan");
//			mTts.setParameter(SpeechSynthesizer.SPEED, "50");
//			mTts.setParameter(SpeechSynthesizer.PITCH, "50");
//			int code = mTts.startSpeaking("体重75公斤。", mTtsListener);
			int code = 0;
			if (code != 0) {
				showTip("start speak error : " + code);
			} else
				showTip("start speak success.");


	}
	
	private BluetoothChatService getMbluechat() {
		return mbluechat;
	}

	public void setMbluechat(BluetoothChatService mbluechat) {
		this.mbluechat = mbluechat;
	}

	@Override
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case BluetoothChatService.MESSAGE_STATE_CHANGE:
			Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
			OnStateChanged(msg);
			break;
		case BluetoothChatService.MESSAGE_WRITE:
			byte[] writeBuf = (byte[]) msg.obj;
			// construct a string from the buffer
			//String writeMessage = new String(writeBuf);
			// mConversationArrayAdapter.add("Me:  " + writeMessage);
			OnMessageWrite(writeBuf,msg.arg1);
			break;
		case BluetoothChatService.MESSAGE_READ:
			byte[] readBuf = (byte[]) msg.obj;
			// construct a string from the valid bytes in the buffer
			///String readMessage = new String(readBuf, 0, msg.arg1);
			// mConversationArrayAdapter.add(mConnectedDeviceName+":  " +
			// readMessage);
			OnMessageRead(readBuf,msg.arg1);
			break;
		case BluetoothChatService.MESSAGE_DEVICE_NAME:
			// save the connected device's name
			// mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
			// Toast.makeText(getApplicationContext(),
			// "Connected to " + mConnectedDeviceName,
			// Toast.LENGTH_SHORT).show();
			OnReceiveDeviceName(msg.getData().getString(BluetoothChatService.DEVICE_NAME));
			break;
		case BluetoothChatService.MESSAGE_TOAST:
			// Toast.makeText(getApplicationContext(),
			// msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
			// .show();
			OnToastMessage(msg.getData().getString(BluetoothChatService.TOAST));
			break;
		}
	}

	static Application app = HealthBoxApplication.getInstance();
	protected void OnStateChanged(Message msg)
	{
		String tip = "";
		Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
        switch (msg.arg1) {
        case BluetoothChatService.STATE_CONNECTED:
        	tip = app.getString(R.string.title_connected_to);
        	showTip(tip + mConnectedDeviceName);        	
            break;
        case BluetoothChatService.STATE_CONNECTING:
        	tip = app.getString(R.string.title_connecting);
        	showTip(tip + mConnectedDeviceName);        	
            break;
        case BluetoothChatService.STATE_LISTEN:
        case BluetoothChatService.STATE_NONE:
        	tip = app.getString(R.string.title_not_connected);
        	showTip(tip + mConnectedDeviceName);        	
            break;
        }
	};
	protected abstract void OnMessageWrite(byte[] msg, int len);
	protected abstract void OnMessageRead(byte[] msg, int len);
	protected void OnReceiveDeviceName(String msg)
	{
		mConnectedDeviceName = msg;
        
	};
	protected void OnToastMessage(String msg)
	{
		
	};
	
		

	private void showTip(final String str) {
		
		if (parent!=null)
		{
		 parent.runOnUiThread(new Runnable() {
				@Override
				 public void run() {
					 Toast.makeText(mContext, str,
			                 Toast.LENGTH_SHORT).show();
				 }
		 });
		}
	}

	protected void write(byte[] response) {
		BluetoothChatService chat = getMbluechat();
		if (chat!=null)
			chat.write(response);
		else
			Log.e(TAG, "blue chat service is null, cant send message");		
	}
	
//	new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//            case BluetoothChatService.MESSAGE_STATE_CHANGE:
//                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
//                switch (msg.arg1) {
//                case BluetoothChatService.STATE_CONNECTED:
//                	tvDeviceName.setText(R.string.title_connected_to);
//                	tvDeviceName.append(mConnectedDeviceName);
//                    break;
//                case BluetoothChatService.STATE_CONNECTING:
//                	tvDeviceName.setText(R.string.title_connecting);
//                    break;
//                case BluetoothChatService.STATE_LISTEN:
//                case BluetoothChatService.STATE_NONE:
//                	tvDeviceName.setText(R.string.title_not_connected);
//                    break;
//                }
//                break;
//            case BluetoothChatService.MESSAGE_WRITE:
//                byte[] writeBuf = (byte[]) msg.obj;
//                // construct a string from the buffer
//                String writeMessage = new String(writeBuf);
//                //mConversationArrayAdapter.add("Me:  " + writeMessage);
//                tvDeviceStatus.setText(writeMessage);
//                break;
//            case BluetoothChatService.MESSAGE_READ:
//                byte[] readBuf = (byte[]) msg.obj;
//                // construct a string from the valid bytes in the buffer
//                String readMessage = new String(readBuf, 0, msg.arg1);
//                //mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
//                updateDash(readMessage);
//                tvDeviceStatus.setText(readMessage);
//                break;
//            case BluetoothChatService.MESSAGE_DEVICE_NAME:
//                // save the connected device's name
//                mConnectedDeviceName = msg.getData().getString(BluetoothChatService.DEVICE_NAME);
//                Toast.makeText(getApplicationContext(), "Connected to "
//                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
//                break;
//            case BluetoothChatService.MESSAGE_TOAST:
//                Toast.makeText(getApplicationContext(), msg.getData().getString(BluetoothChatService.TOAST),
//                               Toast.LENGTH_SHORT).show();
//                break;
//            }
//        }
//    };
}
